//
//  ViewController.m
//  Recoder
//


#import "ViewController.h"
#import "CommonUtil.h"
#include "audio_encoder.hpp"

@interface ViewController ()


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
}


- (IBAction)audioEncoder:(id)sender {
    NSLog(@"FDK AAC Encoder Test....");
    
    NSString *pcmFilePath = [CommonUtil bundlePath:@"music.pcm"];
    NSString *aacFilePath = [CommonUtil documentsPath:@"vocal.aac"];
    
    FILE *aacFileHandle = fopen([aacFilePath cStringUsingEncoding:NSUTF8StringEncoding], "w");
    if (!aacFileHandle) {
        NSLog(@"create file error");
        return;
    }
    fclose(aacFileHandle);
    
    AudioEncoder *encoder = new AudioEncoder();
    int bitsPerSample = 16;
    const char *codec_name = [@"libfdk_aac" cStringUsingEncoding:NSUTF8StringEncoding];
    int bitRate = 128 * 1024;
    int channels = 2;
    int sampleRate = 44100;
    if (encoder->init(bitRate, channels, sampleRate, bitsPerSample, [aacFilePath cStringUsingEncoding:NSUTF8StringEncoding], codec_name) < 0) {
        return;
    }
    
    int buffersize = 1024 * 256;
    byte *buffer = new byte[buffersize];
    FILE *pcmFileHandle = fopen([pcmFilePath cStringUsingEncoding:NSUTF8StringEncoding], "rb");
    size_t readBufferSize = 0;
    while ((readBufferSize = fread(buffer, 1, buffersize, pcmFileHandle)) > 0) {
        encoder->encode(buffer, (int)readBufferSize);
    }
    
    delete[] buffer;
    fclose(pcmFileHandle);
    encoder->destory();
    delete encoder;
    NSLog(@"------finish encoder-----");
}

@end
